package com.mall.common;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
@Component
public class RedisIdWorker {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    //设置起始时间，我这里设定的是2022.01.01 00:00:00
    public static final Long BEGIN_TIMESTAMP = 1672531200L;
    //序列号长度
    public static final Long COUNT_BIT = 32L;

    public long nextId(String keyPrefix){
        //获取当前时间戳
        long current = LocalDateTime.now().toEpochSecond(ZoneOffset.UTC);
        //于起始位置相减,作为全局id的时间戳
        long timeStamp = current - BEGIN_TIMESTAMP;
        //获取当天日期，这样每一个key就对应当天，每天的上限就是2的32次方，并方便统计当天生产id的数量
        String date = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        //使用redis自增
        Long increment = stringRedisTemplate.opsForValue().increment("icr" + keyPrefix + ":" + date);
        //拼接并返回，使用位运算
        return timeStamp << COUNT_BIT | increment;
    }
}
